import React, { useEffect, useState, memo, useRef } from 'react';
import { Table as AntTable } from 'antd';
// @ts-ignore
import $ from 'jquery';
import { Toast } from 'antd-mobile';
// @ts-ignore
import ICharts from '../ICharts';
import Kpi from './Kpi';
import { dataValueFormat, isKpiChart } from '../ChartsConfig';
import { IDrill } from '@/pages/SelfQuery/type';
import { getLastLevelVisualTypeVal, isLevelVisualTypeColumn } from '@/pages/SelfQuery/utils';
import { tableComponents } from './components';
require('./index.less');
require('../index.less');


export interface IColumn {
  title: string;
  dataIndex: string;
  key: string;
  ellipsis: boolean;
  render?: (data: any) => void;
  onCell?: (record: any) => any;
  name?:string

}

interface TableChartProps extends ICharts {
  name?: string
  isDetails?: boolean
  totalDatas?: any
}

const Table: React.FC<TableChartProps> = memo((props) => {
  const { showDataDown, columns, configs, drillsIcon, onSelect, name, totalDatas, isDetails } = props;
  const [records, setRecords] = useState<Array<any>>([]);
  const tableRef = useRef(null);

  useEffect(() => {
    setRecords([]);
    let doc = $('.chartTableTrBg');
    for (let docKey in doc) {
      let node = doc[docKey];
      if (node.className) {
        node.className = '';
      }
    }
  }, [props]);
  useEffect(() => {
    initValue();
  }, [props.data]);

  const initValue = () => {
    const dataSource = setFormat();
    const columns = setColumns();
    if (dataSource.length == 1 && columns.length == 2) {
      onSelect && onSelect(dataSource);
    }
  };

  const dataDown = () => {
    const dataSource = setFormat();
    const columns = setColumns();
    if (dataSource.length == 1 && columns.length == 2) {
      setRecords(dataSource);
    }
    if (records.length == 0) {
      Toast.info('请选择', 2);
      return;
    }
    showDataDown(records);
  };

  /**
   * 设置数据的格式
   */
  const setFormat = () => {
    return dataValueFormat(props);
  };

  /**
   * 设置展示的标题
   */
  const setColumns = () => {
    let aliass: Array<{ key: string; name: string; alias: string }> = [];
    // 设置别名
    const { cols, metrics, drills, model, chartStyles } = configs;
    cols.forEach((col: any) => {
      let alias: any = {};
      alias.key = col.name;
      alias.name = col.name;
      alias.alias = col.field.alias == '' ? col.name : col.field.alias;
      aliass.push(alias);
    });
    metrics.forEach((metric: any) => {
      let alias: any = {};
      let name = `${metric.agg}(${metric.name.split('@')[0]})`;
      alias.key = metric.name;
      alias.name = name;
      alias.alias = metric.field.alias == '' ? name : metric.field.alias;
      aliass.push(alias);
    });
    if (drills) {
      drills.forEach((drill: IDrill) => {
        let alias: any = {};
        let name = drill.name;
        alias.key = name;
        alias.name = name;
        alias.alias = drill.field.alias == '' ? name : drill.field.alias;
        aliass.push(alias);
      });
    }
    if (aliass.length > 0) {
      let dataColumns: IColumn[] = columns.map((v: any) => {
        const name = v.name;
        const column: IColumn = { title: '', dataIndex: '', key: '', ellipsis: false };
        const titles = aliass.filter((alias: any) => alias.name == name);
        column.title = titles.length > 0 ? titles[0].alias : name;
        column.dataIndex = name;
        column.key = name;
        if (isLevelVisualTypeColumn(name, model)) {
          column.render = (text) => {
            return getLastLevelVisualTypeVal(text);
          };
        }
        if (chartStyles.table) {
          const { columnsConfig } = chartStyles.table;
          const columnConfigItem = columnsConfig.find((cfg) => cfg.columnName === titles[0].key);
          if (columnConfigItem) {
            column.onCell = () => ({
              config: columnConfigItem,
            });
          }
        }
        return column;
      });
      return dataColumns;
    }
    return columns;
  };

  const dataSource = setFormat();
  const columnList = setColumns();


  const allData = totalDatas && totalDatas.length ? totalDatas : [];
  let obj: any = {};
  allData.map((v: any) => {
    obj[v.column] = v.total;
  });

  const copyProps = { ...props, ...{ data: [obj] } };
  const footerData = dataValueFormat(copyProps);

  for (let i = 0; i < allData.length; i++) {
    allData[i].column;
  }
  let colSpan = 0
  footerData.map((obj: any) => {
    for (let i = 0; i < allData.length; i++) {
      const value = obj[allData[i].column];
      if (allData[i].totalType === 'totalSum') {
        obj[allData[i].column] = `(总计)${value}`;
      }
      if (allData[i].totalType === 'totalAvg') {
        obj[allData[i].column] = `(平均)${value}`;
      }
      if (allData[i].viewModelType === 'category') {
        obj[allData[i].column] = `合计`;
        colSpan += 1
      }
    }
  });

  let showDataObj = {}; // 合计数据对象
  // 剔除无数据项
  footerData.map((obj: any) => {
    for (let key in obj) {
      if (
        String(obj[key]).indexOf('(总计)') === -1 &&
        String(obj[key]).indexOf('(平均)') === -1 &&
        String(obj[key]).indexOf('合计') === -1
      ) {
        obj[key] = '--';
      }
    }
    showDataObj = obj;
    return obj;
  });
  let footerArr: Array<any> = []; // 合计行展示数据
  columnList.map((item: any) => {
    // @ts-ignore
    if (showDataObj[item.dataIndex]) {
      // @ts-ignore
      footerArr.push(showDataObj[item.dataIndex]);
    }
  });

  let scrollY = 500
  if(tableRef.current && !isDetails) {
    // @ts-ignore
    scrollY = tableRef.current.offsetHeight - 90
  }

  return (
    <div className={`tableBody`} ref={tableRef}>
      {showDataDown ? <div className={`drillBody`}>{drillsIcon(dataDown)}</div> : null}
      {isKpiChart(dataSource, columnList, configs.model) ? (
        <Kpi configs={configs} columns={columnList} dataSource={dataSource} />
      ) : (
        <AntTable
          // @ts-ignore
          rowKey={(record: any, i: number) => i }
          className={`table`}
          components={tableComponents}
          // @ts-ignore
          onRow={(record: any, idx: number) => {
            const isClicked: boolean = records
              .map((v) => JSON.stringify(v))
              .includes(JSON.stringify(record));
              // @ts-ignore
            const node = $(`.ant-table-tbody tr[data-row-key=${idx}]`);
            node.attr('class', isClicked ? 'chartTableTrBg' : '');
            return {
              onClick: (event) => {
                setRecords([record]);
                onSelect && onSelect([record]);
              },
            };
          }}
          scroll={dataSource.length <= 5 ? {} : {y: scrollY} }
          columns={columnList}
          size="middle"
          dataSource={dataSource}
          // @ts-ignore
          pagination={dataSource.length <= 5 ? false : { defaultPageSize: '5', pageSizeOptions: ['5', '10', '20', '50', '100'], }}
          // pagination={false}
          summary={() => {
            return (
              <AntTable.Summary.Row>
                {footerArr.map((v, i) => (
                  // @ts-ignore
                  <AntTable.Summary.Cell index={i + 'total'} colSpan={i === 0 ? colSpan : i > colSpan-1 ? 1 : 0}>{v}</AntTable.Summary.Cell>
                ))}
              </AntTable.Summary.Row>
            );
          }}
        />
      )}
    </div>
  );
});
export default Table;
